package com.rwind.dynamic.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@RestController
public class QueryController {

    public ResponseEntity<String> handleRequests(HttpServletRequest request) throws Exception {
        System.out.println("dynamic requestUrl");
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping("/show")
    public String showData(HttpServletRequest request) {
        return "hello world!";
    }

    @ResponseBody
    public Object myTest4(HttpServletRequest request) {
        byte[] body = new byte[request.getContentLength()];
        JSONObject json = null;
        try {
            ServletInputStream in = request.getInputStream();
            in.read(body, 0, request.getContentLength());
            json = JSON.parseObject(new String(body, "UTF-8"));
        } catch (   IOException e) {
            e.printStackTrace();
        }
        if (Objects.isNull(json)) {
            return JSONObject.parseObject("{\"msg\":\"failure\"}");
        }
        return json;
        //return String.format("name is %s and age is %s", json.getString("name"), json.getString("age"));
    }
}